﻿using LanqiQAwebapi.Dto;
using LanqiQAwebapi.Interface;
using LanqiQAwebapi.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace LanqiQAwebapi.Todo
{
    public class essay : Iessay

    {
        private readonly LanQiQaDBContext _LanQiQaDBContext;

        public essay(LanQiQaDBContext lanQiQaDBContext)
        {

            _LanQiQaDBContext = lanQiQaDBContext;
        }
        /// <summary>
        /// 默认推荐
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public List<Qa> GetEssayAsync(int page = 1, int pagesize = 10)
        {
            var query = _LanQiQaDBContext.Qas.AsQueryable();

            return query.Skip((page - 1) * pagesize).Take(page).ToList();

        }
        /// <summary>
        /// 用户关注的回答没有关注默认推荐
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <param name="CurttrUserid"></param>
        /// <returns></returns>
        public List<Qa> GetEssayByFollowAsync(int page, int pagesize, int CurttrUserid)
        {
            var query = _LanQiQaDBContext.Follows.Where(f => f.UserId == CurttrUserid).SelectMany(f => f.FollowedUser.Qas);
            if (query.Count() > 0)
            {
                return query.Skip((page - 1) * pagesize).Take(page).ToList();//有关注
            }
            else
            {
                var defaultQuery = _LanQiQaDBContext.Qas.AsQueryable();
                return defaultQuery.Skip((page - 1) * pagesize).Take(pagesize).ToList();//无关住
            }
        }
        /// <summary>
        /// 根据用户的指定问题来获取文章
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <param name="questions"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Qa> GetEssayByQuestionAsync(int page, int pagesize, string questions)
        {
            return _LanQiQaDBContext.Qas.Where(o => o.Question == questions).AsQueryable().Skip((page - 1) * pagesize).Take(page).ToList();

        }
        /// <summary>
        /// 获取热榜问题
        /// </summary>
        /// <returns></returns>
        public  List<HotQa> GetHotQuestion()
        {
            int topN = 10;

            var data = _LanQiQaDBContext.Issues
     .Where(issue => !string.IsNullOrEmpty(issue.QuistionName))
     .GroupBy(issue => issue.QuistionName)
     .Select(g => new
     {
         Question = g.Key,                              // 问题名称作为问题文本
         AnswerCount = g.Count(),                       // 回答数量（即该问题出现的次数）
         QaId = g.Min(issue => issue.QaID ?? 0),        // 该问题下最小的 QaID（注意空值处理）
         AnswerContent = g
             .OrderBy(issue => issue.QaID)              // 按 QaID 升序
             .First().ProblemDescription                // 取第一个对应的 ProblemDescription 作为回答内容
     })
     .OrderByDescending(x => x.AnswerCount)
     .Take(topN); // 只取前 N 个最热门的问题
            List<HotQa> hotQaList = new List<HotQa>();

            if (data != null)
            {
                foreach (var item in data)
                {
                    hotQaList.Add(new HotQa
                    {
                        Question = item.Question,
                        AnswerCount = item.AnswerCount,
                        QaId = item.QaId,
                        AnswerContent = item.AnswerContent
                    });
                }
            }

            return hotQaList;
        }
        /// <summary>
        /// 模糊查询问题答案
        /// </summary>
        /// <param name="questionname"></param>
        /// <returns></returns>
        public List<Qa> GetQuestion(string questionname)
        {
            return _LanQiQaDBContext.Qas
          .Where(x => x.Question.Contains(questionname))
          .ToList();


        }
        /// <summary>
        /// 用户搜索回答
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <param name="questions"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Qa> UserSearchAsync(int page, int pagesize, string questions)
        {

            var query = _LanQiQaDBContext.Qas.Where(o => o.Question.Contains(questions)/*||o.TextFilePath.Contains(questions)*/).AsQueryable();

            if (query.Count() > 0)
            {
                return query.Skip((page - 1) * pagesize).Take(page).ToList();
            }
            else
            {
                var defaultquery = _LanQiQaDBContext.Qas.AsQueryable();


                return query.Skip((page - 1) * pagesize).Take(page).ToList();

            }
        }
        /// <summary>
        /// 添加问题
        /// </summary>
        /// <param name="QuestionName"></param>
        /// <returns></returns>
        public async Task<bool> AddQuestionsAsync(AddIssuesDto addIssuesDto)
        {
            try
            {
                var qname = await _LanQiQaDBContext.Issues.Where(c => c.QuistionName == addIssuesDto.questionname).Select(o => o.QuistionName).FirstOrDefaultAsync();
                if (qname == null || qname == "")
                {
                    var newIssues = new Issue
                    {

                        // 主键问题id
                        // public int QuistionId { get; set; }

                        // 问题标题
                        QuistionName = addIssuesDto.questionname,

                        // Qa 表外键 回答id
                        // public int? QaID { get; set; }

                        // 提问人姓名
                        Questioner = addIssuesDto.questioner,

                        // 提问时间
                        /*    public DateTime?*/
                        QuestionTime = DateTime.Now,

                        // 问题描述
                        ProblemDescription = addIssuesDto.questiondesc,
                        UserId = addIssuesDto.questionerid
                    };
                    _LanQiQaDBContext.Issues.Add(newIssues);
                    return await _LanQiQaDBContext.SaveChangesAsync() > 0;
                }
                else { return false; }

            }
            catch (Exception)
            {

                return false;
            }



        }
        /// <summary>
        /// 获取问题ById
        /// </summary>
        /// <returns></returns>
        public List<Qa> GetQuestionById(int id)
        {
            return _LanQiQaDBContext.Qas
           .Where(x => x.QaId == id)
           .ToList();

        }
        /// <summary>
        /// 添加回答
        /// </summary>
        public bool AddAnswer(AddAnswerDto addAnswerDto)
        {
            Qa qa = new Qa
            {
                UserId = addAnswerDto.Userid,
                Question = addAnswerDto.Question,

                AnswerContent = addAnswerDto.AnswerContent
            };

            _LanQiQaDBContext.Qas.Add(qa);
            return _LanQiQaDBContext.SaveChanges() > 0;
        }
        public List<Qa> ShowAnswer(ShowAnswerDto showAnswerDto) 
        {


        var data=    _LanQiQaDBContext.Qas.Where(x=>x.UserId== showAnswerDto.UserId&&x.Question== showAnswerDto.QuestionName).ToList();
            return data;
        }

        public  List<FollowedUserAnswerDto> ShowFollowAnswers(int userID) 
        {


            var followedUsersAnswers = _LanQiQaDBContext.Follows
        .Where(f => f.UserId == userID)
        .Join(
            _LanQiQaDBContext.Qas,
            follow => follow.FollowedUserId,
            qa => qa.UserId,
            (follow, qa) => new FollowedUserAnswerDto
            {
                QaId = qa.QaId,
                Question = qa.Question,
                AnswerContent = qa.AnswerContent,
                SummaryAnswer = qa.SummaryAnswer,
                AgreeCount = qa.AgreeCount,

                UserId = qa.User.UserId,
                UserName = qa.User.UserName,
                AvatarPath = qa.User.AvatarPath,
                UserVip = qa.User.UserVip
            }
        )
        .OrderByDescending(x => x.AgreeCount)
        .ToList();

            return followedUsersAnswers;
        }


    }


}
